/**
 * Notes:  问答后台管理
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2024-08-15 07:48:00 
 */

const BaseProjectAdminService = require('./base_project_admin_service.js');
const dataUtil = require('../../../../framework/utils/data_util.js');
const cloudBase = require('../../../../framework/cloud/cloud_base.js');
const cloudUtil = require('../../../../framework/cloud/cloud_util.js');
const util = require('../../../../framework/utils/util.js');
const QuestionModel = require('../../model/question_model.js');
const AnswerModel = require('../../model/answer_model.js');
const QuestionService = require('../question_service.js');

class AdminQuestionService extends BaseProjectAdminService {

	checkQuestion(obj) {
		if (!obj) return;
		// 中间项不能为空
		if (obj.optionh && !obj.optiong) this.AppError('选项G不能为空');
		if (obj.optiong && !obj.optionf) this.AppError('选项F不能为空');
		if (obj.optionf && !obj.optione) this.AppError('选项E不能为空');
		if (obj.optione && !obj.optiond) this.AppError('选项D不能为空');
		if (obj.optiond && !obj.optionc) this.AppError('选项C不能为空');
		if (obj.optionc && !obj.optionb) this.AppError('选项B不能为空');
		if (obj.optionb && !obj.optiona) this.AppError('选项A不能为空');

		// 选项不为空的个数
		let cnt = 0;
		if (obj.optiona) cnt++;
		if (obj.optionb) cnt++;
		if (obj.optionc) cnt++;
		if (obj.optiond) cnt++;
		if (obj.optione) cnt++;
		if (obj.optionf) cnt++;
		if (obj.optiong) cnt++;
		if (obj.optionh) cnt++;
		let answer = obj.answer.toUpperCase();
		if (answer.length != new Set(answer).size) {
			this.AppError('答案不能有重复字符');
		}

		switch (obj.type) {
			case '单选题': {
				if (cnt < 2) this.AppError('单选题至少2个选项');
				if (answer.length != 1) this.AppError('单选题答案只有一位');
				break;
			}
			case '多选题': {
				if (cnt < 3) this.AppError('多选题至少3个选项');
				if (answer.length == 1) this.AppError('多选题答案至少两位');
				if (answer.length > cnt) this.AppError('本多选题答案不能超过' + cnt + '位');
				break;
			}
			/*
			case '不定项选择题': {
				if (cnt < 2) this.AppError('不定项选择题至少2个选项');
				break;
			}*/
		}

		let reg = /^[A-H]+$/;
		if (cnt == 2) reg = /^[A-B]+$/;
		else if (cnt == 3) reg = /^[A-C]+$/;
		else if (cnt == 4) reg = /^[A-D]+$/;
		else if (cnt == 5) reg = /^[A-E]+$/;
		else if (cnt == 6) reg = /^[A-F]+$/;
		else if (cnt == 7) reg = /^[A-G]+$/;
		else if (cnt == 8) reg = /^[A-H]+$/;

		if (!reg.test(answer) && cnt == 1)
			this.AppError('答案的范围须为A');
		else if (!reg.test(answer) && cnt == 2)
			this.AppError('答案的范围须为A~B');
		else if (!reg.test(answer) && cnt == 3)
			this.AppError('答案的范围须为A~C');
		else if (!reg.test(answer) && cnt == 4)
			this.AppError('答案的范围须为A~D');
		else if (!reg.test(answer) && cnt == 5)
			this.AppError('答案的范围须为A~E');
		else if (!reg.test(answer) && cnt == 6)
			this.AppError('答案的范围须为A~F');
		else if (!reg.test(answer) && cnt == 7)
			this.AppError('答案的范围须为A~G');
		else if (!reg.test(answer) && cnt == 8)
			this.AppError('答案的范围须为A~H');

		obj.answer = answer;
	}

	// 修正值
	fixForms(forms) {
		return forms;
	}

	/**添加 */
	async insertQuestion(question) {
		// 验证必填字段
		if (!question.title || !question.cateId || !question.cateName || !question.forms) {
			this.AppError('题目、分类和表单数据不能为空');
		}
		
		// 验证题目格式
		const questionObj = dataUtil.dbForms2Obj(question.forms);
		this.checkQuestion(questionObj);
		
		// 构建数据对象
		let data = {
			QUESTION_TITLE: question.title.trim(),
			QUESTION_CATE_ID: question.cateId,
			QUESTION_CATE_NAME: question.cateName,
			QUESTION_ORDER: question.order || 0,
			QUESTION_FORMS: question.forms,
			QUESTION_OBJ: questionObj,
			QUESTION_STATUS: question.status || 1, // 默认为启用状态
			QUESTION_ADD_TIME: Date.now(),
		};
		
		// // 添加创建者信息（如果有）
		// if (question.createUser) {
		// 	data.QUESTION_CREATE_USER = question.createUser;
		// }
		
		// 检查是否已存在相同题目
		const existQuestion = await QuestionModel.getOne({
			QUESTION_TITLE: data.QUESTION_TITLE,
			QUESTION_CATE_ID: data.QUESTION_CATE_ID
		});
		if (existQuestion) {
			this.AppError('该分类下已存在相同题目');
		}
		
		// 插入数据库
		try {
			const result = await QuestionModel.insert(data);
			return result;
		} catch (e) {
			this.AppError('题目添加失败：' + e.message);
		}
	}

	/**删除数据 */
	async delQuestion(id) {
		// 检查问题是否存在
		const question = await QuestionModel.getOne({ _id: id });
		if (!question) {
			this.AppError('问题不存在');
		}
		
		// 删除问题
		await QuestionModel.delete(id);
		
		// 级联删除相关答案
		await AnswerModel.del({ ANSWER_QUESTION_ID: id });
		return { success: true };
	}

	async delAnswer(id) {
		// 检查答案是否存在
		const answer = await AnswerModel.getOne({ _id: id });
		if (!answer) {
			this.AppError('答案不存在');
		}
		
		// 删除答案
		await AnswerModel.delete(id);
		return { success: true };
	}

	/**获取信息 */
	async getQuestionDetail(id) {
		let fields = '*';
		let where = {
			_id: id
		};
		let question = await QuestionModel.getOne(where, fields);
		if (!question) return null;
		return question;
	}

// 更新forms信息
	async updateQuestionForms({
		id,
		hasImageForms
	}) {
		return await QuestionModel.editForms(id, 'QUESTION_FORMS', 'QUESTION_OBJ', hasImageForms);
	}

	/**更新数据 */
	async editQuestion({
		id,
		title,
		cateId,
		cateName,
		order,
		forms,
		status
	}) {
		// 检查问题是否存在
		const question = await QuestionModel.getOne({ _id: id });
		if (!question) {
			this.AppError('问题不存在');
		}

		// 验证题目数据
		const questionObj = dataUtil.dbForms2Obj(forms);
		this.checkQuestion(questionObj);

		// 构建更新数据
		const data = {};
		if (title !== undefined) data.QUESTION_TITLE = title;
		if (cateId !== undefined) data.QUESTION_CATE_ID = cateId;
		if (cateName !== undefined) data.QUESTION_CATE_NAME = cateName;
		if (order !== undefined) data.QUESTION_ORDER = order;
		if (forms !== undefined) {
			data.QUESTION_FORMS = forms;
			data.QUESTION_OBJ = questionObj;
		}
		if (status !== undefined) data.QUESTION_STATUS = status;

		// 更新问题
		await QuestionModel.edit(id, data);
		return { success: true };
	}

	/**取得分页列表 */
	async getAdminQuestionList({
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序
		whereEx, //附加查询条件
		page,
		size,
		isTotal = true,
		oldTotal
	}) {
		orderBy = orderBy || {
			'QUESTION_ORDER': 'asc',
			'QUESTION_ADD_TIME': 'desc'
		};
		let fields = '*';

		let where = {};
		where.and = {
		};

		if (util.isDefined(search) && search) {
			where.or = [
				{ QUESTION_TITLE: ['like', search] },
			];
		} else if (sortType && util.isDefined(sortVal)) {
			// 搜索菜单
			switch (sortType) {
				case 'cateId': {
					where.and.QUESTION_CATE_ID = String(sortVal);
					break;
				}
				case 'status': {
					where.and.QUESTION_STATUS = Number(sortVal);
					break
				}
				case 'type': {
					where.and['QUESTION_OBJ.type'] = String(sortVal);
					break
				}
				case 'sort': {
					orderBy = this.fmtOrderBySort(sortVal, 'QUESTION_ADD_TIME');
					break;
				}
			}
		}

		return await QuestionModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);
	}

	/**取得分页列表 */
	async getAdminAnswerList({
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序
		whereEx, //附加查询条件
		page,
		size,
		isTotal = true,
		oldTotal
	}) {
		orderBy = orderBy || {
			'ANSWER_ORDER': 'asc',
			'ANSWER_ADD_TIME': 'desc'
		};
		let fields = 'user.USER_NAME,user.USER_MOBILE,ANSWER_CNT,ANSWER_SUCC_CNT,ANSWER_START,ANSWER_TYPE,ANSWER_PER,ANSWER_DAY,ANSWER_DURATION,ANSWER_END,ANSWER_USER_ID,ANSWER_ADD_TIME,ANSWER_CATE_NAME,ANSWER_SCORE';

		let where = {};
		where.and = {
			ANSWER_TYPE: 1
		};

		if (util.isDefined(search) && search) {
			where.or = [
				{ 'user.USER_NAME': ['like', search] },
				{ 'user.USER_MOBILE': ['like', search] },
			];

		} else if (sortType && util.isDefined(sortVal)) {
			// 搜索菜单
			switch (sortType) {
				case 'cateId': {
					where.and.ANSWER_CATE_ID = String(sortVal);
					break;
				}
				case 'type': {
					where.and['ANSWER_TYPE'] = Number(sortVal);
					break
				}
				case 'sort': {
					orderBy = this.fmtOrderBySort(sortVal, 'ANSWER_ADD_TIME');
					break;
				}
			}
		}

		let UserModel = require('../../model/user_model.js');
		let joinParams = {
			from: UserModel.CL,
			localField: 'ANSWER_USER_ID',
			foreignField: 'USER_MINI_OPENID',
			as: 'user',
		};

		return await AnswerModel.getListJoin(joinParams, where, fields, orderBy, page, size, isTotal, oldTotal);
	}

	/**修改状态 */
	async statusQuestion(id, status) {
		// 检查问题是否存在
		const question = await QuestionModel.getOne({ _id: id });
		if (!question) {
			this.AppError('问题不存在');
		}
		
		// 更新状态
		await QuestionModel.edit(id, { QUESTION_STATUS: status });
		return { success: true };
	}

	async clearQuestion(cateId) {
		if (!cateId) {
			this.AppError('分类ID不能为空');
		}
		
		// 获取该分类下的所有问题
		const questions = await QuestionModel.getList({
			and: { QUESTION_CATE_ID: cateId }
		}, '_id');
		
		// 批量删除问题和答案
		if (questions.list.length > 0) {
			const questionIds = questions.list.map(q => q._id);
			// 删除选中题目
			await QuestionModel.del({ _id: { $in: questionIds } });
			await AnswerModel.del({ ANSWER_QUESTION_ID: { $in: questionIds } });
		}
		
		return { success: true, count: questions.list.length };
	}

	//******************导入 */
	async importQuestion({ cloudId, cateId, cateName }) {
		if (!cloudId || !cateId || !cateName) {
			this.AppError('参数不完整');
		}
		
		// 下载Excel文件
		const res = await cloudUtil.downloadFile(cloudId);
		if (!res || !res.fileContent) {
			this.AppError('文件下载失败');
		}

		// 解析Excel文件 (假设使用xlsx库)
		const xlsx = require('xlsx');
		const workbook = xlsx.read(res.fileContent, { type: 'buffer' });
		const sheet = workbook.Sheets[workbook.SheetNames[0]];
		const data = xlsx.utils.sheet_to_json(sheet);
		
		if (!data || data.length === 0) {
			this.AppError('Excel文件中没有数据');
		}
		
		// 验证并导入题目
		const successList = [];
		const failList = [];
		for (let i = 0; i < data.length; i++) {
			try {
				const row = data[i];
				// console.log(JSON.stringify(row))
				const questionObj = {
					type: row['题型（必填）'],
					title: row['题目（必填）'],
					optiona: row['选项A（必填）'],
					optionb: row['选项B（必填）'],
					optionc: row['选项C'],
					optiond: row['选项D'],
					optione: row['选项E'],
					optionf: row['选项F'],
					optiong: row['选项G'],
					optionh: row['选项H'],
					answer: row['正确答案（必填）'],
					desc: row['答案解析']
				};
				
				// 验证题目格式
				this.checkQuestion(questionObj);
				
				// 转换为表单格式
				const forms = [];
				forms.push({ mark: 'type', title: '题型', type: 'select', val: questionObj.type})
				forms.push({ mark: 'answer', title: '正确答案', type: 'text', val: questionObj.answer})
				forms.push({ mark: 'img', title: '图片', type: 'image', val: questionObj.img })
				forms.push({ mark: 'optiona', title: 'A', type: 'text', val: questionObj.optiona })
				forms.push({ mark: 'optionb', title: 'B', type: 'text', val: questionObj.optionb })
				forms.push({ mark: 'optionc', title: 'C', type: 'text', val: questionObj.optionc })
				forms.push({ mark: 'optiond', title: 'D', type: 'text', val: questionObj.optiond })
				forms.push({ mark: 'optione', title: 'E', type: 'text', val: questionObj.optione })
				forms.push({ mark: 'optionf', title: 'F', type: 'text', val: questionObj.optionf })
				forms.push({ mark: 'optiong', title: 'G', type: 'text', val: questionObj.optiong })
				forms.push({ mark: 'optionh', title: 'H', type: 'text', val: questionObj.optionh })
				forms.push({ mark: 'desc', title: '答案解析', type: 'text', val: questionObj.desc })
				
				// 插入题目
				await this.insertQuestion({
					title: questionObj.title,
					cateId,
					cateName,
					order: i + 1,
					forms
				});
				successList.push(i + 2); // 行号从2开始
			} catch (e) {
				failList.push({
					row: i + 2,
					error: e.message
				});
			}
		}
		
		return {
			success: true,
			total: data.length,
			successList,
			failList
		};
	}
}

module.exports = AdminQuestionService;